import Vue from 'vue';
import VueRouter from 'vue-router';
import HomeView from '../views/HomeView.vue';
//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
	return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter);

const routes = [

	{
		path: '/login',
		name: 'login',
		component: () => import('../views/login/Login'),
		meta: {
			title: '登录',
			requireAuth: false, //添加该字段，表示进入路由是否需要登录
		},
	},
	{
		path: '/',
		name: '',
		component: HomeView,
		redirect: '/', //路由重定向
		meta: {
			title: '首页',
			requireAuth: true, //添加该字段，表示进入路由是否需要登录
		},
		children: [{
				path: '/',
				name: 'imgAdmin',
				component: () => import('@/views/imgAdmin/index'),
				meta: {
					title: '首页图片管理',
					requireAuth: true
				}
			},
			{
				path: '/404',
				name: '404',
				component: () => import('@/views/404'),
				meta: {
					title: '404',
					requireAuth: true, //添加该字段，表示进入路由是否需要登录
				},
			},
			{
				path: '/imgClassAdmin',
				name: 'imgClassAdmin',
				component: () => import('@/views/imgClassAdmin/index'),
				meta: {
					title: '图片管理',
					requireAuth: true
				}
			},
			{
				path: '/administer',
				name: 'administer',
				component: () => import('@/views/administer/index'),
				meta: {
					title: '管理员管理',
					requireAuth: true
				}
			},
			{
				path: '/swiperAdmin',
				name: 'swiperAdmin',
				component: () => import('@/views/swiperAdmin/index'),
				meta: {
					title: '轮播图管理',
					requireAuth: true
				}
			},
		]
	},
];

const router = new VueRouter({
	mode: process.env.VUE_APP_ROUTER_MODE,
	base: process.env.BASE_URL,
	routes,
});
// 路由拦截
router.beforeEach((to, from, next) => {
	if (to.matched.length) { //路由是否存在，不存在跳转404
		if (to.meta.requireAuth) { //是否需要登录
			// 是否已登录
			let token = window.localStorage.getItem('token');
			if (token) {
				//如果用户信息存在则往下执行。
				next()
			} else {
				//如果用户token不存在则跳转到login页面
				if (to.path === '/login') {
					next()
				} else {
					next('/login')
				}
			}
		} else {
			next()
		}
	} else {
		next('/404')
	}
})
export default router;
